//
//  ConfirmPreorderViewController.swift
//  ShareCar
//
//  Created by 久众科技 on 2018/10/24.
//  Copyright © 2018 changqingkeji. All rights reserved.
//

import UIKit
import SnapKit
class ConfirmPreorderViewController: UIViewController {
    
    var car: Car.Detail!
    var durationPackageId: String?
    var currentAddress: String!
    
    @IBOutlet weak var timeBackgroundView: UIControl!
    @IBOutlet weak var dateBackgroundView: UIControl!
    
    @IBOutlet weak var timeHeight: NSLayoutConstraint!
    @IBOutlet weak var dateHeight: NSLayoutConstraint!
    
    @IBOutlet weak var timeBagBtn: UIButton!
    @IBOutlet weak var addTimeBtn: UIButton!
    @IBOutlet weak var sureButton: UIButton!
    @IBOutlet weak var noCountBtn: UIButton!
    
    @IBOutlet weak var timeImageView: UIImageView!
    @IBOutlet weak var dateImageView: UIImageView!
    
    @IBOutlet weak var totalmoneyLabel: UILabel!
    
    @IBOutlet weak var carInfo: CarView!
    @IBOutlet weak var scrollView: UIScrollView!
    
    @IBOutlet weak var timeRoadLabel: UILabel!
    @IBOutlet weak var timeDurationLabel: UILabel!
    @IBOutlet weak var minPriceLabel: UILabel!
    
    @IBOutlet weak var dateRentLabel: UILabel!
    @IBOutlet weak var dateRent2Label: UILabel!
    @IBOutlet weak var otherRentLabel: UILabel!

    @IBOutlet weak var redpackLabel: UILabel!
    @IBOutlet weak var redpackButton: UIButton!
    
    @IBOutlet weak var unCountLabel: UILabel!
    @IBOutlet weak var maxcountLabel: UILabel!
    var selectedDayCount: Int?                            //选择上的日租的天数
    var selectedIndex: Int!
    var orderType: OrderType? {
        didSet {
            if orderType == .time {
                timeBackgroundView.masksToBounds = true
                timeBackgroundView.layer.borderWidth = 2.5
                timeBackgroundView.layer.borderColor = UIColor(hexString: "70bc2f")?.cgColor
                timeBackgroundView.layer.cornerRadius = 4.0
                
                dateBackgroundView.layer.borderWidth = 0
                dateHeight.constant = 60
                timeImageView.image = UIImage(named: "green_ trigon")
                dateImageView.image = UIImage(named: "lowprice")
                totalmoneyLabel.isHidden = true
            } else if orderType == .date {
                dateBackgroundView.masksToBounds = true
                dateBackgroundView.layer.borderWidth = 2.5
                dateBackgroundView.layer.borderColor = UIColor(hexString: "70bc2f")?.cgColor
                dateBackgroundView.layer.cornerRadius = 4.0
                timeBackgroundView.layer.borderWidth = 0
                timeHeight.constant = 60
                timeImageView.image = UIImage(named: "lowprice")
                dateImageView.image = UIImage(named: "green_ trigon")
                if selectedDayCount != nil {
                    totalmoneyLabel.isHidden = false
                }
            }
        }
    }
    
    var data: Car.DayInfo!                                //当前可以预定的天数信息
    var appointDuration = 0                               //加时时长
    var gotoOrderBlock: (() -> ())?
    var allEnable: Bool!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        carInfo.path = .confirmPreodrderCarType
        carInfo.setCar(car: car)
        timeHeight.constant = 60
        dateHeight.constant = 60
        setup()
        //请求预定的天数
        requestCount()
    }
    func setup() {
        allEnable = car.isSupportTimerent == 1 && car.isSupportDaily == 1
        state((car.isSupportTimerent, car.isSupportDaily, allEnable))
        
        if car.isSupportTimerent == 1 {
            timeRoadLabel.text = car.priceData.perkmUnitPrice
            timeDurationLabel.text = car.priceData.perminUnitPrice
            minPriceLabel.text = car.priceData.initiatePrice
            maxcountLabel.text = "每次最高收取\(car.noDeductibles)元"
            
            guard let text = maxcountLabel.text else {
                return
            }
            
            let attrString = NSMutableAttributedString(string: text)
            attrString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor(valueRGB: 0x6c6c8d, alpha: 1.0), range: NSRange(location: 0, length: text.count))
            
            let rangArr = text.hw_exMatchStrRange(String(car.noDeductibles))
            let range = rangArr[0]
            attrString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor(valueRGB: 0x0a0b41, alpha: 1.0), range: range)
            maxcountLabel.attributedText = attrString
        }
        if car.isSupportDaily == 1 {
            dateRentLabel.text = car.dailyPriceData.dailyPrice + "元起"
            otherRentLabel.text = car.dailyPriceData.preparePrice
            unCountLabel.text = car.dailyPriceData.noDeductibles
        }
        
        if car.isRedpackCar == 1 {
            redpackLabel.text = "红包车 " + car.redpackCarData.activityName
            redpackLabel.isHidden = false
            redpackButton.isHidden = false
        }
    }
    
    //MARK: - IBAction
    @IBAction func chooseScheme(_ sender: UIControl) {
        scrollView.setNeedsDisplay()
        UIView.animate(withDuration: 0.25, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: .curveLinear, animations: {
            if sender == self.timeBackgroundView {
                self.state((1, 0, self.allEnable))
            } else if sender == self.dateBackgroundView {
                self.state((0, 1, self.allEnable))
            }
            self.scrollView.layoutIfNeeded()
        })
    }
    
    @IBAction func submitOrder(_ sender: UIButton) {
        
        if !condition() { return }
        if orderType == .time {
            if car.limitTomorrow == 1 {
                alert(title: "提示", message: "该车辆明日限行，是否继续订车?") { [weak self] in
                    if let self = self {
                        self.preorderOrder(car: self.car)
                    }
                }
            } else {
                preorderOrder(car: car)
            }
        } else if orderType == .date {
            self.performSegue(withIdentifier: "agreeProtocolSence", sender: nil)
        }
    }
    
    @IBAction func action(_ sender: Any) {
        performSegue(withIdentifier: "webPageSence", sender: 1)
    }

    @IBAction func countCost(_ sender: UIButton) {
        performSegue(withIdentifier: "webPageSence", sender: 2)
    }
    
    //最下面的一句话
    @IBAction func returnCarOnothercity() {
        performSegue(withIdentifier: "webViewSence", sender: H5page.otherCityreturncar)
    }

    @IBAction func timeBag(_ sender: UIButton) {
        
        if orderType == .time {
            performSegue(withIdentifier: "timeBagSegue", sender: car.projectTimerentId)
        }
        if orderType == .date {
            
            let _ = JZDatePickerView.createDatepickerViewWith(dataSource: data) { [weak self] count in
                if let self = self {
                    let item = self.data.list[count]
                    sender.setTitle("\(item.day)天", for: .normal)
                    self.totalmoneyLabel.isHidden = false
                    self.dateRentLabel.text = item.avgPrice + "元"
                    self.dateRent2Label.text = "/日均租金"
                    self.selectedDayCount = item.day
                    self.selectedIndex = count
                    sender.setTitleColor(UIColor(hexString: "6C6C8D"), for: .normal)
                    self.setData(item)
                }
            }
        }
    }
    
    //设值
    func setData(_ item: Car.DayInfo.DayCount) {
        if let button = self.view.viewWithTag(51) as? UIButton {
            self.totalmoneyLabel.text = button.isSelected ? "预计总金额:\(item.pretotalPrice)" : "预计总金额:\(item.unpretotalPrice)"
        }
    }

    
    @IBAction func chooseAddtime(_ sender: UIButton) {
        let sheet = UIAlertController(title: "时间选择", message: nil, preferredStyle: .actionSheet)
        
        for i in [0, 10, 20, 30, 60] {
            let action = UIAlertAction(title: "\(i)分钟", style: .default) { [weak self] action in
                sender.setTitle("\(i)分钟", for: .normal)
                self?.appointDuration = i
            }
            sheet.addAction(action)
        }
        
        let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        sheet.addAction(cancel)
        
        present(sheet, animated: true, completion: nil)
    }
    
    @IBAction func unCountdecuction(_ sender: UIButton) {
        
        func reset(){
            if sender.tag == 51, selectedDayCount != nil {
                let info = self.data.list[selectedIndex]
                self.setData(info)
            }
        }

        if sender.isSelected {
            alertWithCancelButton(title: "确定不购买此服务?", message: "如未购买不计免赔服务，租赁期间发生交通事故，您需承担所有车辆损失及因维修造成的停运损失（200元/天）", okTitle: "不购买", cancelTitle: "购买") {
                sender.isSelected.toggle()
                reset()
            }
        } else {
            sender.isSelected.toggle()
            reset()
        }
    }
    
    @IBAction func redpack(_ sender: Any) {
        performSegue(withIdentifier: "webViewSence", sender: H5page.redpack)
    }
    
    //MARK: - Custom method
    func preorderOrder(car: Car.Detail) {
        
        guard let type = orderType else {
            showError("选择租车方案")
            return
        }
        JZLoading.showLoadingWith(toView: self.view)
        Order.preorder(carId: car.carId,
                       noDeductibles: noCountBtn.isSelected ? 2 : 1,
                       appointDuration: appointDuration,
                       orderAddress: currentAddress,
                       location: userLocation,
                       rentDays: 0,
                       preorderType: type.rawValue,
                       durationPackageId: durationPackageId,
                       success: { [weak self] data in
                        JZLoading.hideLoading()
                        if let self = self {
                            self.alert(title: "提示", message: "车辆预订成功，系统会为您保留\(self.appointDuration + 15)分钟，超时订单将自动取消。", completion: {
                                
                                self.performSegue(withIdentifier: "preorderSegue", sender: data?.orderId)
                            })
                        }
        }) { [weak self] error, preorder in
            JZLoading.hideLoading()
            if error.code == 2001 {
                if let preorder = preorder, let status = preorder.status {
                    let order = Order.ProgressOrder(orderId: preorder.orderId,
                                                    orderStatus: status,
                                                    forceFlag: preorder.forceFlag,
                                                    orderType: preorder.orderType)
                    self?.goToOrder(progressOrder: order)
                    self?.alert(title: nil, message: error.msg, completion: {
                        self?.gotoOrderBlock?()
                    })
                }
            } else if error.code == 2005 {
                //城市已停运
                self?.alert(title: "", message: error.msg, completion: {
                    //确定
                    self?.performSegue(withIdentifier: "webPageSence", sender: 3)
                })
            } else if error.code == 2030 {
                self?.alertWithCancelButton(title: "预定失败", message: error.msg, completion: {
                    let storyBoard = UIStoryboard(name: "UserInfo", bundle: nil)
                    let vc = storyBoard.instantiateViewController(withIdentifier: "DepositInfoViewController") as! DepositInfoViewController
                    vc.page = .timeRent
                    self?.navigationController?.pushViewController(vc, animated: true)
                })
            } else if error.code == 1005 {
                self?.showError(error)
            } else {
                self?.alert(title: "提示", message: error.msg, completion: nil)
            }
        }
    }
    
    func goToOrder(progressOrder order: Order.ProgressOrder) {
        if order.orderType == 1 {     //时租
            
            if order.forceFlag == 2 {
                gotoOrderBlock = { [weak self] in
                    self?.performSegue(withIdentifier: "CoerceEndOrderSegue", sender: order.orderId)
                }
            } else {
                switch order.orderStatus {
                case .reserve:
                    gotoOrderBlock = { [weak self] in
                        self?.performSegue(withIdentifier: "preorderSegue", sender: order.orderId)
                    }
                case .cancelNoPay:
                    gotoOrderBlock = { [weak self] in
                        self?.performSegue(withIdentifier: "cancelNoPaySegue", sender: order.orderId)
                    }
                case .use:
                    gotoOrderBlock = { [weak self] in
                        self?.performSegue(withIdentifier: "preorderSegue", sender: order.orderId)
                    }
                case .returnCar:
                    gotoOrderBlock = { [weak self] in
                        self?.performSegue(withIdentifier: "returnDetailSegue", sender: order.orderId)
                    }
                case .pay:
                    gotoOrderBlock = { [weak self] in
                        self?.performSegue(withIdentifier: "returnDetailSegue", sender: order.orderId)
                    }
                case .finish:
                    gotoOrderBlock = { [weak self] in
                        self?.performSegue(withIdentifier: "orderUnPaySence", sender: order.orderId)
                    }
                }
            }
        }  else if order.orderType == 2 {    //日租
            if order.forceFlag == 2 {
                gotoOrderBlock = { [weak self] in
                    self?.performSegue(withIdentifier: "coerceEndDayOrder", sender: order.orderId)
                }
            } else {
                switch order.orderStatus {
                case .reserve:
                    gotoOrderBlock = { [weak self] in
                        self?.performSegue(withIdentifier: "ConfirmPaySegue", sender: order.orderId)
                    }
                case .cancelNoPay:
                    break
                case .use:
                    gotoOrderBlock = { [weak self] in
                        self?.performSegue(withIdentifier: "preorderSegue", sender: order.orderId)
                    }
                case .pay, .finish, .returnCar:
                    gotoOrderBlock = { [weak self] in
                        self?.performSegue(withIdentifier: "dayReturnDetailSegue", sender: order.orderId)
                    }
                }
            }
        }
    }
    
    func requestCount() {
        JZLoading.showLoadingWith(toView: view)
        Car.uniformPrice(carId: car.carId, success: { data in
            JZLoading.hideLoading()
            if let data = data {
                self.data = data
            }
        }) { message in
            JZLoading.hideLoading()
            self.showError(message.msg)
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    func state(_ status: (timeer:Int, daily:Int, allisSupport: Bool)) {
        switch status {
        case (timeer:1, daily:0, false):
            timeHeight.constant = 186
            orderType = .time
            dateHeight.constant = 0
            
        case (timeer:0, daily:1, false):
            self.dateHeight.constant = 137
            orderType = .date
            timeHeight.constant = 0
            
        case (timeer:1, daily:0, true):
            if orderType != .time {
                timeHeight.constant = 186
                orderType = .time
            }
            if orderType == .date {
                dateHeight.constant = 60
            }
        case (timeer:0, daily:1, true):
            
            if orderType != .date {
                dateHeight.constant = 137
                orderType = .date
            }
            if orderType == .time {
                timeHeight.constant = 60
            }
        default:break
        }
    }
    
    func condition() -> Bool {
        let storyBoard = UIStoryboard(name: "UserInfo", bundle: nil)
        guard User.isLogin() else {
            let vc = storyBoard.instantiateViewController(withIdentifier: "LoginViewController")
            present(vc, animated: true, completion: nil)
            return false
        }
        
        guard User.isAuthentication() else {
            //人脸识别引导页
            if let user = User.info() {
                switch user.certStep {
                case 0:performSegue(withIdentifier: "gotoAuthPageViewSence", sender: nil)
                case 1:performSegue(withIdentifier: "DrivingLicenseSegue", sender: nil)
                case 2:performSegue(withIdentifier: "ReviewAttentationSegue", sender: nil)
                case 3:performSegue(withIdentifier: "AttentationRejectSegue", sender: nil)
                default:break
                }
            }

            return false
        }
        
        guard orderType != nil else {
            showError("请你选择租车方案")
            return false
        }
        
        if orderType == .date && selectedDayCount == nil {
            showError("请选择日租天数")
            return false
        }
        
        if orderType == .time { //如果是时租
            guard User.isPaydeposit() || User.memberType() == 3 || User.isBoundCard() else {
                let vc = storyBoard.instantiateViewController(withIdentifier: "DepositInfoViewController") as! DepositInfoViewController
                vc.page = .timeRent
                navigationController?.pushViewController(vc, animated: true)
                return false
            }
        } else if orderType == .date {  //如果是日租
            
            guard (User.isPayDaydeposit() && (User.isPaydeposit() || User.memberType() == 3)) || User.isBoundCard() else {
                let vc = storyBoard.instantiateViewController(withIdentifier: "DepositInfoViewController") as! DepositInfoViewController
                vc.page = .dateReserve
                navigationController?.pushViewController(vc, animated: true)
                return false
            }
        }
        
        return true
    }
    
    // MARK: - Navigation
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "timeBagSegue" {
            if let vc = segue.destination as? DurationPackageListViewController {
                vc.projectTimerentId = sender as? String
                vc.sourceFlag = 1
                vc.selectedDurationPackageId = durationPackageId
                vc.selectedPackageBlock = { [weak self] id ,name in
                    self?.timeBagBtn.setTitle(name, for: .normal)
                    self?.timeBagBtn.setTitleColor(UIColor(hexString: "6C6C8D"), for: .normal)
                    self?.durationPackageId = id
                }
            }
        } else if segue.identifier == "webViewSegue" {  //web
            if let nav = segue.destination as? UINavigationController,
                let vc = nav.viewControllers.first as? WebViewController {
                vc.page = Page.server(.otherCityreturncar)
            }
        } else if segue.identifier == "preorderSegue" {
            if let vc = segue.destination as? PreorderViewController {
                vc.orderId = sender as? String
            }
        } else if segue.identifier == "orderUnPaySence" {
            if let vc = segue.destination as? OrderDetailViewController {
                vc.orderId = sender as? String
                vc.page = .debtOrder
            }
        } else if segue.identifier == "CoerceEndOrderSegue" {
            if let vc = segue.destination as? CoerceEndOrderViewController {
                vc.orderId = sender as? String
            }
        } else if segue.identifier == "cancelNoPaySegue" {   //取消订单支付
            if let vc = segue.destination as? CancelOrderPayViewController {
                vc.orderId = sender as? String
            }
        } else if segue.identifier == "returnDetailSegue" { //支付
            if let vc = segue.destination as? ReturnDetailViewController {
                vc.orderId = sender as? String
            }
        } else if segue.identifier == "agreeProtocolSence" { //租车协议
            if let nav = segue.destination as? UINavigationController {
                if let vc = nav.viewControllers.first as? ProtocolViewController {
                    vc.commit = { [weak self] pvc in
                        guard let self = self else {
                            return
                        }
                        
                        guard let type = self.orderType else {
                            return
                        }
                        
                        let b: UIButton?
                        
                        switch type {
                        case .time:
                            b = self.view.viewWithTag(50) as? UIButton
                        case .date:
                            b = self.view.viewWithTag(51) as? UIButton
                        case .preorder:
                            b = nil
                        }
                        
                        JZLoading.showLoadingWith(toView: self.view)
                        Order.preorder(carId: self.car.carId,
                                       noDeductibles: b?.isSelected ?? false ? 2 : 1,
                                       appointDuration: self.appointDuration,
                                       orderAddress: self.currentAddress,
                                       location: self.userLocation,
                                       rentDays: self.selectedDayCount ?? 0,
                                       preorderType: type.rawValue,
                                       durationPackageId: self.durationPackageId,
                                       success: { [weak self] data in
                                        JZLoading.hideLoading()
                                        
                                        pvc.navigationController?.dismiss(animated: false, completion: {
                                            self?.performSegue(withIdentifier: "ConfirmPaySegue", sender: data?.orderId)
                                        })
                        }) { [weak self] error, preorder in
                            JZLoading.hideLoading()
                            switch error.code {
                            case 2001:
                                if let preorder = preorder, let status = preorder.status {
                                    let order = Order.ProgressOrder(orderId: preorder.orderId,
                                                                    orderStatus: status,
                                                                    forceFlag: preorder.forceFlag,
                                                                    orderType: preorder.orderType)
                                    self?.goToOrder(progressOrder: order)
                                    pvc.alert(title: nil, message: error.msg, completion: {
                                        pvc.navigationController?.dismiss(animated: false, completion: {
                                            self?.gotoOrderBlock?()
                                        })
                                    })
                                }
                            case 2005:
                                //城市已停运
                                pvc.alert(title: "", message: error.msg, completion: {
                                    //确定
                                    pvc.navigationController?.dismiss(animated: false, completion: {
                                        self?.performSegue(withIdentifier: "webPageSence", sender: 3)
                                    })
                                })
                                
                            case 2030:
                                pvc.alertWithCancelButton(title: "预定失败", message: error.msg, completion: {
                                    let storyBoard = UIStoryboard(name: "UserInfo", bundle: nil)
                                    let vc = storyBoard.instantiateViewController(withIdentifier: "DepositInfoViewController") as! DepositInfoViewController
                                    vc.page = .dateReserve
                                    pvc.navigationController?.pushViewController(vc, animated: true)
                                })
                            default:
                                pvc.alert(title: "", message: error.msg, completion: nil)
                            }
                        }
                    }
                }
            }
            
        } else if segue.identifier == "webPageSence" {
            if let nav = segue.destination as? UINavigationController,
                let vc = nav.viewControllers.first as? WebViewController,
                let sender = sender as? Int {
                switch sender {
                case 1:vc.page = Page.server(.unCountDamage)
                case 2:vc.page = Page.server(.unCountDamage)
                case 3:vc.page = Page.URL("http://h5.9zcap.com/event-h5/20181030/index.html")
                default:break
                }
            }
        } else if segue.identifier == "webViewSence" {
            if let nav = segue.destination as? UINavigationController,
                let vc = nav.viewControllers.first as? WebViewController {
                if let value = sender as? H5page {
                    vc.page = Page.server(value)
                }
            }
        } else if segue.identifier == "ConfirmPaySegue" {
            if let vc = segue.destination as? ConfirmPayViewController {
                vc.orderId = sender as? String
            }
        }
    }
}
